// pages/rankList/rankList.js
var app = getApp();
const pathLevel = '../../../../'; //路径层级
const quote = require(pathLevel + 'utils/quote.config.js') //统一引入文件
const mta = quote.mta;
const api = quote.api;
const tools = quote.tools;
const path = quote.paths;

Page({
    /**
     * 页面的初始数据
     */
    data: {
        path: path,
        QID: null,
        openid: null,
        pushFrom: null,
        User_Score: null, //用户录音得分
        User_PlayTimes: null, //用户录音播放次数
        User_PointPraise: null, //用户录音获得点赞数
        User_RankingNumber: null, //用户录音排名
        User_ImgUrl: null, //用户微信头像
        User_IsPraise: null,
        loadingHidden: false,

        videoTitle: null, //视频标题
        videoUrl: null, //视频播放域名地址
        playUrl: null, //视频链接
        ImgUrl: null, //视频封面

        RankingList: null, //排行榜数据
        srtTimeList: null, //字幕文件
        voiceList: null, //录音文件
        voiceSrc: null, //录音地址
        isPlaying: -1, //是否正在播放
        selectIndex: -1, //当前操作的行数
        isMuted: false, //是否静音播放
        audioContext: wx.createInnerAudioContext(),
        isStop: false, //是否强制停止
        thisTime: -1, //当前视频播放时间
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

        var self = this

        console.log("当前界面的数据", options)

        mta.Page.init();

        if (!options.hasOwnProperty("QID")) {
            wx.switchTab({
                url: `/${path.index}`,
            })
            return;
        }


        self.setData({
            QID: options.QID,
            openid: app.globalData.openId,
            videoUrl: app.globalData.videoUrl,
            User_ImgUrl: app.globalData.userInfo.avatarUrl || '',
        })
        self.getRankData()

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        var self = this

        //视频播放控制
        self.videoContext = wx.createVideoContext('rankVideo')

        //音频播放控制
        self.data.audioContext = wx.createInnerAudioContext()

        var audioContext = self.data.audioContext;
        audioContext.onPlay(function() {
            console.log('音频播放开始');
            self.setData({
                isMuted: true
            })
        });
        audioContext.onStop(function() {
            console.log('音频播放停止');
            self.setData({
                isMuted: false
            })
        });
        audioContext.onEnded(function() {
            console.log('音频播放结束');
            self.setData({
                isMuted: false
            })
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        var self = this

        self.videoContext.pause();
        self.data.audioContext.destroy();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function(params) {
        var that = this;

        that.getRankData(function(params) {
            //数据加载完后停止刷新
            setTimeout(() => {
                console.log('停止刷新');
                wx.stopPullDownRefresh();
            }, 1000);
        })

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    // 上拉触顶函数
    upper: function() {

        // console.log('到顶部了');
    },

    // 下拉触底函数
    lower: function() {

        // console.log('到底了');
    },

    // 滑动函数
    scroll: function(e) {

        // console.log(e);
    },

    // 获取排行榜数据
    getRankData: function(cb) {

        var self = this

        var dataDic = {
            QID: self.data.QID,
            OpenId: app.globalData.openId,
        };

        api.methodGetRankingList({
            dataDic,
            success: (res) => {
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    if (res.data.data) {
                        self.setData({
                            srtTimeList: res.data.data.VideoSrtList,
                            videoTitle: res.data.data.Question_Title,
                            playUrl: res.data.data.Question_VideoUrl,
                            ImgUrl: res.data.data.Question_ImgUrl,
                            User_Score: res.data.data.User_Score,
                            User_PlayTimes: res.data.data.User_PlayTimes,
                            User_PointPraise: res.data.data.User_PointPraise,
                            User_IsPraise: res.data.data.User_IsPraise,
                            User_RankingNumber: res.data.data.User_RankingNumber,
                            User_ImgUrl: res.data.data.User_ImgUrl || app.globalData.userInfo.avatarUrl,
                            RankingList: res.data.data.RankingList,
                        })
                        setTimeout(() => {
                            self.setData({
                                loadingHidden: true
                            })
                        }, 500);
                    }
                }
            },
            fail: (res) => {
                console.log(res);
                wx.showModal({
                    title: '温馨提示',
                    showCancel: false,
                    content: '数据请求失败',
                });
            },
            complete: (res) => {
                console.log(res.data);
                typeof cb == 'function' && cb();
            }
        })
    },

    // 点赞
    praiseOnce: function(res) {
        var self = this
        var praiseOpenId = res.currentTarget.dataset.openid

        app.aldstat.sendEvent('排行榜-用户点赞');
        mta.Event.stat("rankinglist_userspraise", {});

        if (praiseOpenId) {
            var dataDic = {
                OpenId: praiseOpenId,
                QID: self.data.QID,
                OpenId_Points: app.globalData.openId,
            }

            api.methodWeiXinUserPointPraise({
                dataDic,
                success: (res) => {
                    if (res.data.code != 0) {} else {
                        //点赞成功,刷新界面数据
                        self.getRankData()
                        wx.showToast({
                            title: " 点赞成功 ",
                        })
                    }
                },
                fail: (res) => {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: '点赞失败',
                    });
                },
                complete: (res) => {
                    console.log(res.data);
                }
            });
        }
    },

    //点击播放用户录音和视频
    playRecord: function(res) {
        var self = this
        var praiseOpenId = res.currentTarget.dataset.openid
        var indexId = res.currentTarget.dataset.id

        app.aldstat.sendEvent('排行榜-点击用户的录音');
        mta.Event.stat("rankinglist_clickusersrecord", {});

        self.setData({
            isMuted: false,
            isPlaying: -1 //先将其他播放的状态进行改变
        })

        self.videoContext.pause();
        self.data.audioContext.pause();

        if (praiseOpenId) {
            var dataDic = {
                OpenId: praiseOpenId,
                QID: self.data.QID,
                POpenId: app.globalData.openId,
            }

            //获取用户录音
            api.methodGetUserVoice({
                dataDic,
                success: (res) => {
                    console.log(res.data)
                    if (res.data.code != 0) {
                        wx.showModal({
                            title: '温馨提示',
                            showCancel: false,
                            content: res.data.msg,
                        })
                        return;
                    } else {
                        if (res.data.data.VoiceList.length) {
                            // 获取录音文件
                            self.setData({
                                voiceList: res.data.data.VoiceList,
                                isPlaying: indexId,
                                isStop: false
                            })

                            //播放视频 和 用户录音
                            self.playVideoWithTime(0)

                        } else {
                            wx.showModal({
                                title: '温馨提示',
                                showCancel: false,
                                content: "录音文件从地球上消失了！",
                            })
                            return;
                        }
                    }
                },
                fail: (res) => {
                    console.log(res);
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: '数据请求失败',
                    });
                },
                complete: (res) => {
                    wx.hideLoading();
                    console.log(res.data);
                }
            })
        }
    },

    //暂停用户录音和视频
    pauseRecord: function(res) {
        var self = this

        self.videoContext.pause();
        self.data.audioContext.pause();
        self.data.audioContext.stop();

        self.setData({
            isPlaying: -1,
            isMuted: false,
            isStop: true,
        })
    },

    // 播放视频和录音 （新版 播放整个视频 在录音的时间段播放录音）
    playVideoWithTime: function(index) {
        var self = this

        if (!self.data.srtTimeList || !self.data.voiceList || index >= self.data.srtTimeList.length || index >= self.data.voiceList.length || self.data.isStop) {

            self.setData({
                isPlaying: -1,
                isMuted: false,
            })

            self.videoContext.pause();
            self.data.audioContext.pause();
            self.data.audioContext.stop();
            return
        }

        self.videoContext.seek(0.01)
        self.videoContext.play()
    },

    bindTimeUpdate: function(video) {
        var self = this

        // 通过audio的属性秒数计算当前分钟和秒数
        var currentTime = parseInt(video.detail.currentTime);
        console.log('视频当前的播放时间', currentTime);
        if (self.data.thisTime == currentTime) {
            return
        } else {
            self.setData({
                thisTime: currentTime
            })
        }

        if (!self.data.srtTimeList || !self.data.voiceList) {
            return
        }

        for (var index = 0; index < self.data.srtTimeList.length; index++) {
            var startEnd = self.data.srtTimeList[index].Start_End
            var timeArr = startEnd.split("-")
            var startPosition = parseInt(timeArr[0])
            var endPosition = parseInt(timeArr[1]) + 1

            if (startPosition == currentTime) {
                if (self.data.voiceList[index].hasOwnProperty("user_voice_file")) {
                    var voiceFile = app.globalData.apiUrl + self.data.voiceList[index].user_voice_file //app.globalData.apiUrl
                    self.data.audioContext.src = voiceFile
                    self.data.audioContext.stop();
                    self.data.audioContext.play();
                    console.log(startPosition, index, self.data.isMuted, voiceFile)
                }
            }
        }
    },

    bindPause: function(video) {
        var self = this

        self.videoContext.pause();
        self.data.audioContext.pause();
        self.data.audioContext.stop();

        self.setData({
            isPlaying: -1,
            isMuted: false,
            isStop: true,
        })
    },

    bindended: function(video) {
        var self = this

        self.videoContext.pause();
        self.data.audioContext.pause();
        self.data.audioContext.stop();

        self.setData({
            isPlaying: -1,
            isMuted: false,
            isStop: true,
        })
    },
})